package com.cby.olive.sample

import android.content.Context
import android.net.ConnectivityManager
import android.os.Bundle
import android.text.Html
import android.view.View
import androidx.fragment.app.Fragment
import com.cby.android.olive.ext.bind
import com.cby.android.olive.ext.logE
import com.cby.android.olive.ext.logI
import com.cby.android.olive.ext.showToast
import com.cby.android.olive.utils.HandlerUtil
import com.cby.android.olive.utils.NetworkUtils
import com.cby.android.olive.utils.PingUtils
import com.cby.android.olive.utils.ThreadPoolUtil
import com.cby.olive.sample.databinding.FragmentHomeBinding
import java.lang.reflect.Method
import java.net.InetAddress
import java.net.UnknownHostException


/**
 * Description:HomeFragment
 *
 * @author chenbaoyang
 * @create 2023/6/16 14:52
 */
class HomeFragment : Fragment(R.layout.fragment_home) {

    private val binding by lazy { bind<FragmentHomeBinding>() }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.tvTitle.text = "首页"
        binding.tvTitle.text = Html.fromHtml("<span style=\"color: #d4380d;\">红色</span><span style=\"color: #389e0d;\">绿色</span><span\n" +
                "style=\"color: #f5db4d;\">黄色</span><span style=\"color: #3658e2;\">蓝色</span><br />")

        binding.btnNetworkCheck.setOnClickListener {
            ThreadPoolUtil.execute {
                if (isNetworkConnected()) {
                    // 网络正常
                    HandlerUtil.runOnMainThread {
                        showToast("网络正常")
                    }

                } else {
                    // 网络不正常
                    HandlerUtil.runOnMainThread {
                        showToast("网络不正常")
                    }

                }
            }

        }
    }

    /**
     * 用来判断当前应用是否有对应的网络
     */
    private fun isNetworkConnected(): Boolean {
        val connectivityManager = requireActivity().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
        val activeNetwork = connectivityManager!!.activeNetworkInfo
        if (NetworkUtils.isConnected(requireContext())) {
             try {
                 val result = InetAddress.getByName("www.baidu.com")
                 println("chenby1111 == is net Connect result = $result")
                 return !result.equals("");
            } catch (e: UnknownHostException) {
                 println("chenby1111 == is net Connect result = UnknownHostException")
                false
            }
        }
        return false
    }

    private fun clearDns() {
        try {
            val cls = Class.forName("android.os.NetworkUtils")
            val method: Method = cls.getMethod("flushVmDnsCache")
            method.invoke(null)
            "DNS cache cleared successfully".logI()
        } catch (e: Exception) {
            e.printStackTrace()
            "Failed to clear DNS cache".logE()
        }
    }
}